package com.heima.controller;


import com.alibaba.fastjson.JSON;
import com.heima.domain.HhPatient;
import com.heima.dto.SaveDto;
import com.heima.service.IHhPatientService;
import com.heima.thread.UserThreadLocal;
import com.heima.vo.Result;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 就诊人 前端控制器
 * </p>
 *
 * @author 黑马程序员
 * @since 2023-01-29
 */
@RestController
@RequestMapping("/patient")
public class HhPatientController {

    @Autowired
    private IHhPatientService iHhPatientService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;


    @GetMapping("/list")
    public Result getList(){

        // 查询当前登陆用户
        Integer userId = UserThreadLocal.getUserLocal();

        // 查询Redis
        // Redis接口缓存的key命名方式为：当前接口名称+接口查询条件
        String cache = redisTemplate.opsForValue().get("patientList:user_" + userId);

        // 如果有数据，就直接返回，不要访问Mysql
        if (StringUtils.isNotEmpty(cache)){
            // 将Redis中查出来的JSON数据，转回mysql查询出来的结构List<HhPatient>

            List<HhPatient> hhPatient = JSON.parseArray(cache, HhPatient.class);


            return Result.success(hhPatient);

        }

        // 如果没数据，就查询Mysql，并在Mysql查询结束后，回一份数据到Redis
        return Result.success(iHhPatientService.getList());
    }

    @GetMapping
    public Result getPatientById(@RequestParam Integer patientId){
        return Result.success(iHhPatientService.getPatientById(patientId));
    }

    @PostMapping("/remove")
    public Result delPatientById(@RequestParam Integer patientId){
        iHhPatientService.delPatientById(patientId);
        return Result.success(null);
    }


    @PostMapping("/save")
    public Result savePatient(@RequestParam(defaultValue = "") Integer patientId,@RequestBody SaveDto saveDto){
        if (patientId==null){
            iHhPatientService.addPatient(saveDto);
        }else {
            iHhPatientService.updatePatientById(patientId,saveDto);
        }

        return Result.success(null);
    }


}

